`
https://leetcode.cn/problems/furthest-building-you-can-reach/
`

/**
 * @param {number[]} heights
 * @param {number} bricks
 * @param {number} ladders
 * @return {number}
 */
var furthestBuilding = function (heights, bricks, ladders) {
  const n = heights.length

  const diff = []
  for (let i = 1; i < n; i++) {
    diff.push(heights[i] - heights[i - 1])
  }

  // 能否到达第 k 个下标建筑
  const check = (k) => {
    let curBrick = bricks
    // 倒序排列
    const ds = diff.slice(0, k).sort((a, b) => b - a)
    // 前面最大的高度差用梯子抵掉
    let i = ladders
    // 再慢慢消耗砖块
    while (i < ds.length && ds[i] > 0) {
      curBrick -= ds[i++]
      if (curBrick < 0) return false
    }
    return true
  }

  let left = 0, right = n
  while (left + 1 < right) {
    const mid = left + Math.floor((right - left) / 2)
    if (check(mid)) {
      left = mid
    } else {
      right = mid
    }
  }
  return left
};